package com.colter.project.sample.thread.part05.test1;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.TimeUnit;

//异步执行
public class Test4 {
	public static void main(String[] args) {
		ForkJoinPool pool = new ForkJoinPool();
		FolderProcessor system = new FolderProcessor("C:\\Program Files", "exe");
		FolderProcessor program = new FolderProcessor("G:\\PDF", "pdf");
		FolderProcessor document = new FolderProcessor("C:\\Users\\LC\\Documents", "sql");

		pool.execute(system);
		pool.execute(program);
		pool.execute(document);

		do {
			System.out.println("***************************");

			System.out.println("Main:Thread Count:" + pool.getActiveThreadCount());
			System.out.println("Main:Thread Steal:" + pool.getStealCount());
			System.out.println("Main: Parallelism:" + pool.getParallelism());
			System.out.println("Main: Task Queued:" + pool.getQueuedTaskCount());

			System.out.println("***************************");

			try {
				TimeUnit.SECONDS.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		} while ((!system.isDone()) || (!program.isDone()) || (!document.isDone()));
		
		
		pool.shutdown();
		
		List<String> results;
		results = system.join();
		System.out.println("system:"+results.size());
		results = program.join();
		System.out.println("program:"+results.size());
		results = document.join();
		System.out.println("document:"+results.size());
		
	}
}

class FolderProcessor extends RecursiveTask<List<String>> {

	private static final long serialVersionUID = 3671076306599070561L;

	private String path;
	private String extension;

	public FolderProcessor(String path, String extension) {
		super();
		this.path = path;
		this.extension = extension;
	}

	@Override
	protected List<String> compute() {
		List<String> list = new ArrayList<>();
		List<FolderProcessor> tasks = new ArrayList<>();
		File file = new File(path);
		File content[] = file.listFiles();
		if (content != null) {
			for (int i = 0; i < content.length; i++) {
				if (content[i].isDirectory()) {
					FolderProcessor task = new FolderProcessor(content[i].getAbsolutePath(), extension);
					task.fork();
					tasks.add(task);
				} else {
					if (checkFile(content[i].getName())) {
						list.add(content[i].getAbsolutePath());
					}
				}

			}
		}

		if (tasks.size() > 50) {
			System.out.println("Task run." + file.getAbsolutePath() + " " + tasks.size());
		}

		addResultsFromTasks(list, tasks);
		return list;
	}

	private void addResultsFromTasks(List<String> list, List<FolderProcessor> tasks) {
		for (FolderProcessor item : tasks) {
			list.addAll(item.join());
		}
	}

	private boolean checkFile(String name) {
		return name.endsWith(extension);
	}
}
